package com.kstech.exccheck.domain.check;

import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.kstech.exccheck.R;
import com.kstech.exccheck.config.vo.DeviceVO;
import com.kstech.exccheck.config.vo.SubDeviceVO;
import com.kstech.exccheck.db.CheckRecordDao;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.util.ViewTemplateUtil;
import com.kstech.exccheck.view.check.CheckRecordListAdspter;
import com.kstech.exccheck.view.check.OpenCheckRecordActivity;

public class DeviceDialogLoadTask extends
		AsyncTask<Integer, Integer, List<DeviceVO>> {
	// 后面尖括号内分别是参数（线程休息时间），进度(publishProgress用到)，返回值 类型

	private OpenCheckRecordActivity activity;
	private ProgressDialog mProgressDialog = null;
	private TextView deviceIdTV,subdeviceIdTV,checkFinishTimeTV,checkStatusTV,excIdTV;
	// 弹出窗口
	private AlertDialog.Builder builder;
	private AlertDialog dialog;
	// 被选中的机型与子机型单元格
	private LinearLayout selectedColumlayout,selectedSubColumlayout;
	LinearLayout currentSelectedRecord;

	public DeviceDialogLoadTask(TextView deviceIdTV,TextView subdeviceIdTV,TextView checkFinishTimeTV,
								TextView checkStatusTV,TextView excIdTV,OpenCheckRecordActivity activity,LinearLayout currentSelectedRecord) {
		this.deviceIdTV = deviceIdTV;
		this.subdeviceIdTV = subdeviceIdTV;
		this.checkFinishTimeTV = checkFinishTimeTV;
		this.checkStatusTV = checkStatusTV;
		this.excIdTV = excIdTV;
		this.activity = activity;
		this.currentSelectedRecord = currentSelectedRecord;
	}

	/*
	 * 第一个执行的方法 执行时机：在执行实际的后台操作前，被UI 线程调用
	 * 作用：可以在该方法中做一些准备工作，如在界面上显示一个进度条，或者一些控件的实例化，这个方法可以不用实现。
	 *
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
		mProgressDialog = new ProgressDialog(AppContext.context);
		// 设置进度条风格，风格为圆形，旋转的
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

		// 设置ProgressDialog 提示信息
		mProgressDialog.setMessage("正在加载机型信息，请稍等。。。");

		// 设置ProgressDialog 的进度条是否不明确
		mProgressDialog.setIndeterminate(false);
		// 设置ProgressDialog 是否可以按退回按键取消
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
	}

	/**
	 * 主要实现类 执行时机：在onPreExecute 方法执行后马上执行，该方法运行在后台线程中 作用：主要负责执行那些很耗时的后台处理工作。可以调用
	 * publishProgress方法来更新实时的任务进度。该方法是抽象方法，子类必须实现。
	 *
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected List<DeviceVO> doInBackground(Integer... params) {
		return AppContext.getResConfig().getDeviceList();
	}

	/*
	 * 执行时机：这个函数在doInBackground调用publishProgress时被调用后，UI
	 * 线程将调用这个方法.虽然此方法只有一个参数,但此参数是一个数组，可以用values[i]来调用
	 * 作用：在界面上展示任务的进展情况，例如通过一个进度条进行展示。此实例中，该方法会被执行100次
	 *
	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	 */
	@Override
	protected void onProgressUpdate(Integer... values) {
		// mTextView.setText(values[0]+"%");
		super.onProgressUpdate(values);
	}

	/*
	 * 执行时机：在doInBackground 执行完成后，将被UI 线程调用 作用：后台的计算结果将通过该方法传递到UI 线程，并且在界面上展示给用户
	 * result:上面doInBackground执行后的返回值，所以这里是"执行完毕"
	 *
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(final List<DeviceVO> result) {
		super.onPostExecute(result);
		// 展示机型选择dialog
		LayoutInflater inflater = (LayoutInflater) AppContext.context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.device_dialog, null);
		TableLayout deviceDialogDeviceTableLayout = (TableLayout) view
				.findViewById(R.id.deviceDialogDeviceTableLayout);
		TableLayout deviceDialogSubDeviceTableLayout = (TableLayout) view
				.findViewById(R.id.deviceDialogSubDeviceTableLayout);

		Button deviceDialogBtnSure = (Button) view
				.findViewById(R.id.deviceDialogBtnSure);
		deviceDialogBtnSure.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (selectedColumlayout != null) {
					deviceIdTV.setText(((TextView) selectedColumlayout.getChildAt(0))
							.getText());
				}
				if (selectedSubColumlayout != null) {
					subdeviceIdTV.setText(((TextView) selectedSubColumlayout.getChildAt(0))
							.getText());
				} else {
					subdeviceIdTV.setText("");
				}
				dialog.cancel();
				// 重新加载列表
				ListView listView = (ListView) activity.findViewById(R.id.checkRecordList);
				List<CheckRecordEntity> list = CheckRecordDao.findCheckRecordByCondition(checkFinishTimeTV.getText().toString(), CheckRecordStatusEnum.getCode(checkStatusTV.getText().toString()),
						excIdTV.getText().toString(),deviceIdTV.getText().toString(),subdeviceIdTV.getText().toString());
				listView.setAdapter(new CheckRecordListAdspter(activity, list));
				listView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
											long arg3) {
						currentSelectedRecord = (LinearLayout) arg1;
					}
				});
			}
		});

		Button deviceDialogBtnClose = (Button) view
				.findViewById(R.id.deviceDialogBtnClose);
		deviceDialogBtnClose.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog.cancel();
			}
		});

		final List<DeviceVO> deviceList = AppContext.getResConfig().getDeviceList();
		// 整行数
		int whole = deviceList.size() / 3;
		// 余数
		int remain = deviceList.size() % 3;
		// 总行数
		int trTotal = remain == 0 ? whole : whole + 1;

		for (int i = 0; i < trTotal; i++) {
			ViewTemplateUtil tru = new ViewTemplateUtil(AppContext.context);
			TableLayout tb = tru.getDeviceTableLayout();
			TableRow tr = (TableRow) tb.getChildAt(0);

			for (int j = 0; i == trTotal - 1 && remain != 0 ? j < remain
					: j < 3; j++) {
				// 赋值列列单元格
				LinearLayout ly = (LinearLayout) tr.getChildAt(j);
				TextView deviceName = (TextView) ly.getChildAt(0);
				TextView deviceId = (TextView) ly.getChildAt(2);
				deviceName.setText(deviceList.get(3 * i + j).getDeviceName());
				deviceId.setText(deviceList.get(3 * i + j).getDeviceId());

				// 单元格机型下的子机型数据
				List<SubDeviceVO> subList = deviceList.get(3 * i + j)
						.getSubDeviceList();
				// 监听机型列单元格点击事件
				setColumListener(ly, subList, deviceDialogSubDeviceTableLayout);
			}

			tb.removeView(tr);
			deviceDialogDeviceTableLayout.addView(tr);
		}
		builder = new AlertDialog.Builder(AppContext.context);
		builder.setView(view);
		dialog = builder.create();

		mProgressDialog.cancel();

		dialog.show();
		// end
	}
	/**
	 * 监听机型单元格列点击事件
	 * @param columlayout
	 * @param subList
	 */
	private void setColumListener(final LinearLayout columlayout,
								  final List<SubDeviceVO> subList,final TableLayout deviceDialogSubDeviceTableLayout) {
		columlayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (selectedColumlayout != null) {
					// 重置上一个机型，取消选中状态
					((TextView) selectedColumlayout.getChildAt(0))
							.setTextColor( AppContext.context.getResources().getColor(
									R.color.deviceTextColor));
					selectedColumlayout.getChildAt(1).setVisibility(
							View.GONE);
				}
				selectedColumlayout = columlayout;
				// 设置当前点击机型被选中
				((TextView) columlayout.getChildAt(0))
						.setTextColor(AppContext.context.getResources().getColor(
								R.color.deviceSecectedTextColor));
				columlayout.getChildAt(1).setVisibility(View.VISIBLE);
				selectedSubColumlayout = null;
				// 设置子机型区域布局
				setSubDeviceLayout(subList);
			}

			private void setSubDeviceLayout(List<SubDeviceVO> subList) {
				// 移除所有子机型区域的视图
				deviceDialogSubDeviceTableLayout.removeAllViews();

				// 重新加载子机型区域视图
				for (int k = 0; k < subList.size(); k++) {
					ViewTemplateUtil tru = new ViewTemplateUtil(AppContext.context);
					TableLayout tb = tru.getSubDeviceTableLayout();
					TableRow tr = (TableRow)tb.getChildAt(0);

					// 赋值列列单元格
					final LinearLayout subColumlayout = (LinearLayout)tr.getChildAt(0);
					TextView deviceName = (TextView) subColumlayout.getChildAt(0);
					TextView deviceId = (TextView) subColumlayout.getChildAt(2);
					deviceName.setText(subList.get(k).getSubDevName());
					deviceId.setText(subList.get(k).getSubDevId());

					// 监听子机型点击事件
					subColumlayout.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View arg0) {
							if (selectedSubColumlayout != null) {
								// 重置上一个机型，取消选中状态
								((TextView) selectedSubColumlayout
										.getChildAt(0))
										.setTextColor(AppContext.context.getResources().getColor(
												R.color.deviceTextColor));
								selectedSubColumlayout.getChildAt(1)
										.setVisibility(View.GONE);
							}
							selectedSubColumlayout = subColumlayout;
							// 设置当前点击机型被选中
							((TextView) subColumlayout.getChildAt(0))
									.setTextColor(AppContext.context.getResources().getColor(
											R.color.deviceSecectedTextColor));
							subColumlayout.getChildAt(1).setVisibility(
									View.VISIBLE);
						}
					});

					tb.removeView(tr);
					deviceDialogSubDeviceTableLayout.addView(tr);
				}
			}

		});
	}
}